<template>
  <el-form
      ref="clueRefForm"
      :model="clueQuery"
      :rules="clueRules"
      label-width="100px"
      style="max-width: 95%;">

    <el-form-item label="负责人" prop="ownerId">
      <el-select
          v-model="clueQuery.ownerId"
          placeholder="请选择负责人"
          style="width: 100%"
          clearable
          disabled>
        <el-option
            v-for="item in ownerOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"/>
      </el-select>
    </el-form-item>

    <el-form-item label="所属活动">
      <el-select
          v-model="clueQuery.activityId"
          placeholder="请选择所属活动"
          style="width: 100%"
          clearable>
        <el-option
            v-for="item in activityOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"/>
      </el-select>
    </el-form-item>

    <el-form-item label="姓名" prop="fullName">
      <el-input v-model="clueQuery.fullName"/>
    </el-form-item>

    <el-form-item label="称呼">
      <el-select
          v-model="clueQuery.appellation"
          placeholder="请选择称呼"
          style="width: 100%"
          clearable>
        <el-option
            v-for="item in appellationOptions"
            :key="item.id"
            :label="item.typeValue"
            :value="item.id"/>
      </el-select>
    </el-form-item>

    <el-form-item label="手机" v-if="clueQuery.id > 0"><!--说明的编辑-->
      <el-input v-model="clueQuery.phone" disabled/>
    </el-form-item>

    <el-form-item label="手机" prop="phone" v-else><!--说明是录入-->
      <el-input v-model="clueQuery.phone"/>
    </el-form-item>

    <el-form-item label="微信">
      <el-input v-model="clueQuery.weixin"/>
    </el-form-item>

    <el-form-item label="QQ" prop="qq">
      <el-input v-model="clueQuery.qq"/>
    </el-form-item>

    <el-form-item label="邮箱" prop="email">
      <el-input v-model="clueQuery.email"/>
    </el-form-item>

    <el-form-item label="年龄" prop="age">
      <el-input v-model="clueQuery.age"/>
    </el-form-item>

    <el-form-item label="职业">
      <el-input v-model="clueQuery.job"/>
    </el-form-item>

    <el-form-item label="年收入" prop="yearIncome">
      <el-input v-model="clueQuery.yearIncome"/>
    </el-form-item>

    <el-form-item label="住址">
      <el-input v-model="clueQuery.address"/>
    </el-form-item>

    <el-form-item label="贷款">
      <el-select
          v-model="clueQuery.needLoan"
          placeholder="请选择是否需要贷款"
          style="width: 100%"
          clearable>
        <el-option
            v-for="item in needLoanOptions"
            :key="item.id"
            :label="item.typeValue"
            :value="item.id"/>
      </el-select>
    </el-form-item>

    <el-form-item label="意向状态">
      <el-select
          v-model="clueQuery.intentionState"
          placeholder="请选择意向状态"
          style="width: 100%"
          clearable>
        <el-option
            v-for="item in intentionStateOptions"
            :key="item.id"
            :label="item.typeValue"
            :value="item.id"/>
      </el-select>
    </el-form-item>

    <el-form-item label="意向产品">
      <el-select
          v-model="clueQuery.intentionProduct"
          placeholder="请选择意向产品"
          style="width: 100%"
          clearable>
        <el-option
            v-for="item in productOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"/>
      </el-select>
    </el-form-item>

    <el-form-item label="线索状态">
      <el-select
          v-model="clueQuery.state"
          placeholder="请选择线索状态"
          style="width: 100%"
          clearable>
        <el-option
            v-for="item in clueStateOptions"
            :key="item.id"
            :label="item.typeValue"
            :value="item.id"/>
      </el-select>
    </el-form-item>

    <el-form-item label="线索来源">
      <el-select
          v-model="clueQuery.source"
          placeholder="请选择线索来源"
          style="width: 100%"
          clearable>
        <el-option
            v-for="item in sourceOptions"
            :key="item.id"
            :label="item.typeValue"
            :value="item.id"/>
      </el-select>
    </el-form-item>

    <el-form-item label="线索描述" prop="description">
      <el-input
          v-model="clueQuery.description"
          :rows="5"
          type="textarea"
          placeholder="请输入线索描述"/>
    </el-form-item>

    <el-form-item label="下次联系时间">
      <el-date-picker
          v-model="clueQuery.nextContactTime"
          type="datetime"
          style="width: 100%;"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="请选择下次联系时间"/>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="addClueSubmit">提 交</el-button>
      <el-button type="success" plain @click="goBack">返 回</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import {doGet, doPost, doPut} from "@/http/httpRequest";
import {goBack, messageTip} from "@/util/util";

export default {
  name: "ClueItemView",

  data() {
    return {
      //要录入的表单线索对象，初始值是空
      clueQuery: {},
      //要录入的线索表单验证规则
      clueRules: {
        phone : [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern : /^1[3-9]\d{9}$/, message: '手机号码格式有误', trigger: 'blur'},
          { validator: this.checkPhone, trigger: 'blur' } //方法验证
        ],
        fullName : [
          { min: 2, message: '密码长度至少2个汉字', trigger: 'blur' },
          { pattern : /^[\u4e00-\u9fa5]{0,}$/, message: '姓名必须是中文汉字', trigger: 'blur'} //正则从网上找，然后测试一下对不对，chatgpt
        ],
        qq : [
          { min: 5, message: 'QQ号至少为5位', trigger: 'blur'},
          { pattern : /^\d+$/, message: 'QQ号码必须为数字', trigger: 'blur'},
        ],
        email : [
          { type : 'email', message: 'Email格式有误', trigger: 'blur'}
        ],
        age : [
          { pattern : /^\d+$/, message: '年龄必须为数字', trigger: 'blur'},
          { validator: this.checkAge, trigger: 'blur' } //方法验证
        ],
        yearIncome : [
          { pattern : /^[0-9]+(\.[0-9]{2})?$/, message: '年收入必须是整数或者两位小数', trigger: 'blur'}
        ],
        description : [
          { min: 5, max: 255, message: '线索描述长度为5-255个字符', trigger: 'blur' }
        ]
      },
      //负责人的下拉列表数据，初始值是空
      ownerOptions: [{}],
      //所属活动的下拉选项数据，初始值是空
      activityOptions: [{}],
      //称呼的下拉选项数据，初始值是空
      appellationOptions: [{}],
      needLoanOptions: [{}],
      intentionStateOptions: [{}],
      clueStateOptions: [{}],
      sourceOptions: [{}],
      productOptions : [{}]
    }
  },

  mounted() {
    //加载负责人
    this.loadOwner();
    //加载登录人信息
    this.loadLoginUser();
    this.loadEffectiveActivity();
    this.loadDicValue('appellation');
    this.loadDicValue('needLoan');
    this.loadDicValue('intentionState');
    this.loadDicValue('clueState');
    this.loadDicValue('source');
    this.loadProduct();
    //判断是否需要查询线索详情信息（编辑时就需要查）
    this.loadClueDetail();
  },

  methods : {
    //声明一下返回函数
    goBack,

    //加载负责人
    loadOwner() {
      doGet("/api/user/owner", {}).then(resp => {
        if (resp.data.code === 200) {
          this.ownerOptions = resp.data.data;
        }
      })
    },

    //加载登录人信息
    loadLoginUser() {
      doGet("/api/login/info", {}).then(resp => {
        if (resp.data.code === 200) {
          let loginUser = resp.data.data;
          this.clueQuery.ownerId = loginUser.id;
        }
      })
    },

    //加载正在进行的市场活动（没有在进行的活动不加载）
    loadEffectiveActivity() {
      doGet("/api/activity/effective", {}).then(resp => {
        if (resp.data.code === 200) {
          this.activityOptions = resp.data.data;
        }
      })
    },

    //加载字典数据
    loadDicValue(typeCode) {
      doGet("/api/dic/" + typeCode, {}).then(resp => {
        if (resp.data.code === 200) {
          if (typeCode === 'appellation') {
            this.appellationOptions = resp.data.data
          } else if (typeCode === 'needLoan') {
            this.needLoanOptions = resp.data.data
          } else if (typeCode === 'intentionState') {
            this.intentionStateOptions = resp.data.data
          } else if (typeCode === 'clueState') {
            this.clueStateOptions = resp.data.data
          } else if (typeCode === 'source') {
            this.sourceOptions = resp.data.data
          }
        }
      })
    },

    //加载在售的产品
    loadProduct() {
      doGet("/api/product/sale", {}).then(resp => {
        if (resp.data.code === 200) {
          this.productOptions = resp.data.data;
        }
      })
    },

    //验证手机号的方法
    checkPhone(rule, value, callback) {
      console.log(rule);
      console.log(value); //value就是当前input框里面输入的手机号
      console.log(callback);
      doGet("/api/clue/" + value, {}).then(resp => {
        if (resp.data.code === 500) {//返回状态码500表示手机号存在，返回200表示手机号不存在
          return callback(new Error('该手机号已经录入过，不能在录入.'))
        } else {
          return callback();
        }
      })
    },

    //验证年龄
    checkAge(rule, value, callback) {
      if (value) {
        if (value <= 0) {
          return callback(new Error('年龄不能是负数'))
        } else if (value >= 200) {
          return callback(new Error('年龄不合法'))
        } else {
          //验证通过
          return callback();
        }
      } else {
        //验证通过
        return callback();
      }
    },

    //录入线索（提交保存）
    addClueSubmit() {
      this.$refs.clueRefForm.validate( (isValid) => {
        if (isValid) {
          //当要提交的参数比较多的时候，可以使用FormData提交，代码更简洁一些
          let formData = new FormData(); //FormData是js对象
          for (let field in this.clueQuery) {
            //循环clueQuery对象，把该对象中的所有字段和值都追加到formData
            if (this.clueQuery[field]) {
              formData.append(field, this.clueQuery[field]);
            }
          }
          //编辑
          if (this.clueQuery.id > 0) {
            doPut("/api/clue", formData).then( resp => {
              if (resp.data.code === 200) {
                //编辑成功
                messageTip("编辑成功", "success");
                //不是刷新页面，而是跳转到市场活动列表页
                this.$router.push("/dashboard/clue");
              } else {
                //编辑失败
                messageTip("编辑失败，原因：" + resp.data.msg, "error");
              }
            })
          } else {//新增
            doPost("/api/clue", formData).then( resp => {
              if (resp.data.code === 200) {
                //录入成功
                messageTip("录入成功", "success");
                //不是刷新页面，而是跳转到市场活动列表页
                this.$router.push("/dashboard/clue");
              } else {
                //录入失败
                messageTip("录入失败，原因：" + resp.data.msg, "error");
              }
            })
          }
        }
      })
    },

    //加载线索详情
    loadClueDetail() {
      //线索id
      let id = this.$route.params.id;
      if (id) { //id存在，id有值，id不是空
        doGet("/api/clue/detail/" + id, {}).then(resp => {
          if (resp.data.code === 200) {
            this.clueQuery = resp.data.data;
          }
        })
      }
    }
  }
}
</script>

<style scoped>

</style>